package me.yushuai.wukong.base.controller;

import me.yushuai.wukong.base.api.LocApi;
import me.yushuai.wukong.base.api.dto.CreateLocationDTO;
import me.yushuai.wukong.base.api.dto.LocDTO;
import me.yushuai.wukong.base.api.dto.UpdateLocationDTO;
import me.yushuai.wukong.base.api.request.PagingSearchLocationRequest;
import me.yushuai.wukong.base.entity.Location;
import me.yushuai.wukong.base.service.LocService;
import me.yushuai.wukong.common.dto.PageDTO;
import me.yushuai.wukong.common.error.WuKongException;
import me.yushuai.wukong.common.exceptin.NotExistException;
import me.yushuai.wukong.common.mvc.BaseController;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.web.bind.annotation.RestController;

import javax.persistence.criteria.Predicate;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

/**
 * 库位控制器
 *
 * @author zhoushuai@189.cn
 * @since 2022-08-31
 */
@RestController
public class LocController extends BaseController implements LocApi {

    /**
     * 库位业务类
     */
    private final LocService locService;

    @Autowired
    public LocController(LocService locService) {
        this.locService = locService;
    }

    @Override
    public Long createLocation(CreateLocationDTO dto) throws WuKongException {
        return this.locService.createLocation(dto);
    }

    @Override
    public Long editLocation(Long id, UpdateLocationDTO dto)
            throws WuKongException {
        dto.setId(id);
        return this.locService.updateLocation(dto);
    }

    @Override
    public Long deleteLocation(Long id) throws WuKongException {
        this.locService.deleteLocation(id);
        return id;
    }

    @Override
    public LocDTO getById(Long id) throws NotExistException {
        return this.locService.findById(id);
    }

    @Override
    public PageDTO<LocDTO> pagingSearchLocation(PagingSearchLocationRequest request) {

        Specification<Location> spec = (root, query, criteriaBuilder) -> {
            List<Predicate> predicates = new ArrayList<>();

            if (Objects.nonNull(request.getLocId())) {
                predicates.add(criteriaBuilder.equal(root.get(Location.ID), request.getLocId()));
            }

            return criteriaBuilder.and(predicates.toArray(Predicate[]::new));
        };

        return this.locService.pageSearchLoc(request, spec);
    }

    @Override
    public boolean existById(Long locId) {
        return this.locService.checkHasExistLocationId(locId);
    }

}
